package com.zkc.zblog.controller;

import com.baidu.ueditor.ActionEnter;
import com.zkc.zblog.imagesutils.FileUploadUtils;
import com.zkc.zblog.imagesutils.Global;
import com.zkc.zblog.utils.Dto;
import com.zkc.zblog.utils.DtoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@Api( description = "百度富文本编辑器")
public class UeditorController{



    /**
     *这个接口对应 ueditor.config.js 中的，服务器统一请求接口路径
     *
     * */
    @ApiOperation(value = "这个接口对应 ueditor.config.js 中的，服务器统一请求接口路径")
    @GetMapping("/config")
    public void config(String action, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 百度富文本编辑器的图片上传功能
     * */
    @ApiOperation(value = "百度富文本编辑器的图片上传功能")
    @PostMapping("/config2")
    @ResponseBody
    public String updateAvatar(@ApiParam(value = "图片的流") @RequestParam("imgFile") MultipartFile imgFile) throws IOException {
        /*判断图片不为空*/
        if (!imgFile.isEmpty()) {
            File fileDir = Global.getImgDirFile();
            String avatar = FileUploadUtils.upload(fileDir, imgFile);
            String config =
                    "{\n" +
                            "            \"state\": \"SUCCESS\",\n" +
                            "                \"url\": \""+avatar+"\",\n" +
                            "                \"title\": \"path\",\n" +
                            "                \"original\": \"path\"\n" +
                            "        }";
            return config;
        }
        return "修改头像失败！";
    }











}


